﻿using System;
using System.Text.RegularExpressions;
using WorkItemAnalyser.Core.Assertions;

namespace WorkItemAnalyser.Core.Parsers
{
    public class TextFieldAssertionParser : IAssertionParser
    {
        const string StatusRuleGrammer = @"must be (?<value>.*)";
        const string FullRuleGrammer = @"must have (?<field>.*) of (?<value>.*)";

        public IAssertion ParseAssertion(string assertionText)
        {
            bool isFullGrammer = true;

            if (string.IsNullOrWhiteSpace(assertionText))
                return null;

            if (assertionText.StartsWith("must be", StringComparison.OrdinalIgnoreCase))
            {
                isFullGrammer = false;
            }   

            var ruleExpression = new Regex(isFullGrammer ? FullRuleGrammer : StatusRuleGrammer);
            var matches = ruleExpression.Match(assertionText);

            var fieldName = isFullGrammer ? matches.Groups["field"].ToString() : "State";
            var value = matches.Groups["value"].ToString();

            if (string.IsNullOrWhiteSpace(fieldName) || (string.IsNullOrWhiteSpace(value)))
                return null;

            return new FieldAssertion(fieldName, value);
        }
    }
}
